<template>
  <div class="inbound-confirmation-form">
    <!-- 页面标题 -->
    <div class="page-title">
      <h2>{{ pageTitle }}</h2>
    </div>

    <!-- 功能按钮区 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleBack">返回</el-button>
    </div>

    <!-- 表单内容 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="form-container"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <div class="section-title">基本信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="入库确认编号" prop="code">
              <el-input v-model="formData.code" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库确认日期" prop="confirmDate">
              <el-date-picker
                v-model="formData.confirmDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择入库类型" style="width: 100%">
                <el-option label="成品入库" value="成品入库" />
                <el-option label="还资入库" value="还资入库" />
                <el-option label="拆装入库" value="拆装入库" />
                <el-option label="半成品报废入库" value="半成品报废入库" />
                <el-option label="申请直接入库" value="申请直接入库" />
                <el-option label="库管直接入库" value="库管直接入库" />
                <el-option label="采购入库" value="采购入库" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="关联项目" prop="project">
              <el-input
                v-model="formData.project"
                placeholder="请选择关联项目"
                class="input-with-search"
              >
                <template #append>
                  <el-button :icon="Search" @click="handleSearchProject" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库库管" prop="manager">
              <el-input
                v-model="formData.manager"
                placeholder="请选择库管"
                class="input-with-search"
              >
                <template #append>
                  <el-button :icon="Search" @click="handleSearchManager" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联入库申请单" prop="relatedApplication">
              <el-input
                v-model="formData.relatedApplication"
                placeholder="请选择关联入库申请单"
                class="input-with-search"
              >
                <template #append>
                  <el-button :icon="Search" @click="handleSearchApplication" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="入库确认主题" prop="subject">
              <el-input
                v-model="formData.subject"
                type="textarea"
                :rows="2"
                placeholder="请输入入库确认主题"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 入库明细 -->
      <div class="form-section">
        <div class="section-title">入库明细</div>
        <div class="table-operations">
          <el-button type="primary" @click="handleAddDetail">新增明细</el-button>
          <el-button @click="handleImportDetail">导入明细</el-button>
          <el-button @click="handleDeleteDetail">删除明细</el-button>
        </div>
        <el-table
          ref="detailTableRef"
          :data="formData.details"
          style="width: 100%"
          border
          @selection-change="handleDetailSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" type="index" width="50" />
          <el-table-column label="物料编码" prop="materialCode" min-width="120">
            <template #default="scope">
              <el-input
                v-model="scope.row.materialCode"
                placeholder="请选择物料"
                class="input-with-search"
              >
                <template #append>
                  <el-button :icon="Search" @click="handleSearchMaterial(scope.$index)" />
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" prop="materialName" min-width="150" />
          <el-table-column label="规格型号" prop="specification" min-width="120" />
          <el-table-column label="单位" prop="unit" width="80" />
          <el-table-column label="应入库数量" prop="expectedQuantity" width="100">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.expectedQuantity"
                :min="0"
                :precision="2"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column label="确认入库数量" prop="actualQuantity" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.actualQuantity"
                :min="0"
                :precision="2"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" min-width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 其他信息 -->
      <div class="form-section">
        <div class="section-title">其他信息</div>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { inboundAPI } from '@/api/modules/inbound'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const detailTableRef = ref(null)

// 判断是新增还是修改模式
const isEdit = computed(() => !!route.query.id)
const pageTitle = computed(() => isEdit.value ? '修改入库确认' : '新增入库确认')

// 表单数据
const formData = reactive({
  id: '',
  code: '',
  confirmDate: new Date(),
  type: '',
  project: '',
  manager: '',
  relatedApplication: '',
  subject: '',
  remark: '',
  details: []
})

// 表单校验规则
const rules = {
  confirmDate: [{ required: true, message: '请选择入库确认日期', trigger: 'change' }],
  type: [{ required: true, message: '请选择入库类型', trigger: 'change' }],
  manager: [{ required: true, message: '请选择入库库管', trigger: 'blur' }],
  subject: [{ required: true, message: '请输入入库确认主题', trigger: 'blur' }]
}

// 选中的明细行
const selectedDetails = ref([])

// 处理明细表格选择变化
const handleDetailSelectionChange = (selection) => {
  selectedDetails.value = selection
}

// 新增明细行
const handleAddDetail = () => {
  formData.details.push({
    materialCode: '',
    materialName: '',
    specification: '',
    unit: '',
    expectedQuantity: 0,
    actualQuantity: 0,
    remark: ''
  })
}

// 导入明细
const handleImportDetail = () => {
  ElMessage.info('导入明细功能开发中')
}

// 删除明细
const handleDeleteDetail = () => {
  if (selectedDetails.value.length === 0) {
    ElMessage.warning('请选择要删除的明细行')
    return
  }
  
  const selectedIds = selectedDetails.value.map(item => item.id)
  formData.details = formData.details.filter(item => !selectedIds.includes(item.id))
  ElMessage.success('删除成功')
}

// 搜索相关方法
const handleSearchProject = () => {
  ElMessage.info('选择项目功能开发中')
}

const handleSearchManager = () => {
  ElMessage.info('选择库管功能开发中')
}

const handleSearchApplication = () => {
  ElMessage.info('选择入库申请单功能开发中')
}

const handleSearchMaterial = (index) => {
  ElMessage.info(`选择第${index + 1}行物料功能开发中`)
}

// 保存表单
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const saveData = {
      ...formData,
      id: isEdit.value ? route.query.id : undefined
    }
    
    try {
      if (isEdit.value) {
        await inboundAPI.update(route.query.id, saveData)
      } else {
        const { data } = await inboundAPI.create(saveData)
        formData.id = data
      }
      ElMessage.success('保存成功')
      handleBack()
    } catch (error) {
      console.error('保存失败:', error)
      ElMessage.error('保存失败')
    }
  } catch (error) {
    console.error('表单校验失败:', error)
    ElMessage.error('请完善必填信息')
  }
}

// 返回列表页
const handleBack = () => {
  router.push('/warehouse/inbound-confirmation')
}

// 加载详情数据
const loadDetail = async (id) => {
  try {
    const { data } = await inboundAPI.getDetail(id)
    Object.assign(formData, data)
    return true
  } catch (error) {
    console.error('加载详情失败:', error)
    ElMessage.error('加载详情失败')
    return false
  }
}

// 组件挂载时
onMounted(async () => {
  // 如果是修改模式，加载详情数据
  if (isEdit.value) {
    await loadDetail(route.query.id)
  }
  
  // 如果有关联申请单信息，自动填充
  const { relatedApplicationId, relatedApplication } = route.query
  if (relatedApplicationId && relatedApplication) {
    formData.relatedApplication = relatedApplication
    try {
      const { data } = await inboundAPI.getByApplicationId(relatedApplicationId)
      Object.assign(formData, data)
    } catch (error) {
      console.error('加载关联申请单信息失败:', error)
      ElMessage.error('加载关联申请单信息失败')
    }
  }
})
</script>

<style scoped>
.inbound-confirmation-form {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.page-title {
  margin-bottom: 20px;
}

.page-title h2 {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin: 0;
  padding: 0;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 8px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.form-container {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 30px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.table-operations {
  margin-bottom: 15px;
  display: flex;
  gap: 8px;
}

.input-with-search {
  width: 100%;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-table .el-input) {
  margin-top: 2px;
  margin-bottom: 2px;
}

:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-button) {
  font-weight: 400;
  padding: 8px 16px;
}
</style>